from src.util.Service import *


# 查询所有的菜单 （分页）
def getMenuAll():
    return Menu.getAllMenus()


# 查询所有的菜单 (分页 查询id 菜单名)
def getMenuName(page: Page = Page()):
    Menus = Menu.getAllMenuName(page)
    return Menus


# 修改菜单信息（除了mid）
def updateMenu(data: dict):
    try:
        m_id = data['mId']
        data = formatParam(data, ['mId', "createTime"])
        if not authParam(data.get('status'), ['1', '0']):
            return False
        if not authParam(data.get('faceShow'), ['1', '0']):
            return False
        if not authParam(data.get('iconType'), ['user', 'sys', 'none']):
            return False
        Menu.updateMenu(m_id, data)
        return True
    except:
        return False


# 添加菜单
def addMenu(data: dict):
    try:
        formatParam(data, ['mId'])
        data['status'] = '1'
        data['faceShow'] = '1'
        data["createTime"] = datetime.utcnow()
        if not authParam(data['iconType'], ['user', 'sys', 'none']):
            return False
        Menu.addMenu(data)
    except:
        return False
    return True


# 删除菜单 
def delMenu(mids: list[int]):
    # 在用户角色映射表中删除 mid 的映射关系
    database.transaction()
    try:
        with database.atomic():
            if Menu.MenuHasChild(mids):
                return '请先删除所选菜单下的子菜单'
            tags = MenuButton.getAllMenuHandleTags(mids)
            Menu.delMenuInMId(mids)
            MenuButton.delMenuHandleInMid(mids)
            GroupAuth.delAuthByTypeAndAuth(mids, 'menu')
            GroupAuth.delAuthByTypeAndAuth(tags, 'button')
            RoleButton.delRoleButtonInTag(tags)
            RoleMenu.delRoleMenuInMid(mids)
            database.commit()
    except:
        database.rollback()
        return False
    return True


# 查询菜单上的所有按钮
def getMenuHandles(mid):
    return MenuButton.getAllMenuHandleInMids([mid])


# 更新菜单上的按钮
def updateMenuHandles(mid: int, data: list[dict]):
    try:
        database.begin()
        # 提取旧标签
        oldTags = MenuButton.getAllMenuHandleTags([mid])
        MenuButton.delMenuHandleInMid([mid])
        data = formatParam(data, ['id'])
        for d in data:
            d['mId'] = mid
            if d.get('tag') in oldTags:
                oldTags.remove(d.get('tag'))
        # 删除已经不存在的映射关系
        RoleButton.delRoleButtonInTag(oldTags)
        MenuButton.addMenuHandle(data)
        database.commit()
        return True

    except Exception as e:
        database.rollback()
        assert Exception
        return False
